﻿namespace TingSLsocket

open System
open System.Threading
open System.Collections.Generic

[<Sealed>]
type LockSendController<'t>() =
    let m_queue = new Queue<'t>()
    let m_syncroot = new obj()
    let mutable m_busy = false

    let unSafeEnqueueOrSend item =
        match m_busy with
        | true -> 
            m_queue.Enqueue(item)
            false,Unchecked.defaultof<'t>
        | false ->
            m_busy <- true
            true,item

    let unSafeDequeueAndSend () =
        try
            let item = m_queue.Dequeue()
            true,item
        with
            | :? InvalidOperationException ->
                // the queue is empty
                m_busy <- false
                false,Unchecked.defaultof<'t>

    member this.EnqueueOrSend item =
        lock m_syncroot (fun() -> unSafeEnqueueOrSend item )

    member this.DequeueAndSend () =
        lock m_syncroot unSafeDequeueAndSend 
    

            

            
